import json
import os
import eventlet
from flask_mqtt import Mqtt
from flask_socketio import SocketIO
from flask_cors import CORS
eventlet.monkey_patch()
os.environ["LANG"] = "en_US.UTF-8"
from flask import Flask, request, render_template

app = Flask(__name__, template_folder='templates')
app.config['MQTT_BROKER_URL'] = '118.195.165.129'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_KEEPALIVE'] = 60
app.config['MQTT_USERNAME'] = 'admin'
app.config['MQTT_PASSWORD'] = 'admin'
CORS(app)

mqtt = Mqtt(app)
socketio = SocketIO(app)
import base64
imei = ''


@socketio.on('publish')
def handle_publish(json_str):
    data = json.loads(json_str)
    mqtt.publish(data['topic'], data['message'])


@mqtt.on_connect()
def handle_connect(client, userdata, flags, rc):
    print('on_connect')
    mqtt.subscribe('qingping/582D34401B38/down')


@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
    global imei
    str = bytes.decode(message.payload)
    print(message.payload)


@app.route('/', methods=['GET'])
def index():
    handle_publish(json.dumps({"topic": "123", 'message': '1111111111'}))
    return '成功'


if __name__ == '__main__':
    socketio.run(app, host='127.0.0.1', port=2345, use_reloader=True, debug=True)